package com.test25_常用类2;

import org.junit.Test;

import java.util.Optional;

/**
 * Optional类，保证存储的数据不为null
 * JDK1.8之后
 */
public class Demo03_Optional {

    @Test
    public void test1() {
        // 传统工厂返回的数据可能为空
        IMessage messageObject = Factory.getInstance();
        if (messageObject != null) {
            messageObject.send("沐言优拓：www.yootk.com");
        }
    }

    @Test
    public void test2() {
        Optional<String> optional = Optional.of("沐言优拓：www.yootk.com");
        if (optional.isPresent()) { // 有数据保存
            System.out.println(optional.get());
        }
    }

    @Test
    public void test3() {
        // 不允许设置空数据
        Optional<String> optional = Optional.of(null);
    }

    @Test
    public void test4() {
        // 可以保证返回的数据不为空
        IMessage messageObject = Factory2.getInstance().get();
        messageObject.send("沐言优拓：www.yootk.com");
    }
}

@FunctionalInterface
interface IMessage {
    public void send(String msg);
}

class Factory {
    private Factory() {
    }

    public static IMessage getInstance() {
        return null;
    }
}

/**
 * 通过Optional改进工厂类
 */
class Factory2 {
    private Factory2() {
    }

    public static Optional<IMessage> getInstance() {
        return Optional.of((msg) -> {
            System.out.println("【消息发送】" + msg);
        });
    }
}
